package com.smartwebx.fr.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.smartwebx.fr.bean.SimpleUseArgConf;
import com.smartwebx.fr.service.StoredProcService;
import com.smartwebx.fr.service.ckeditor.UseArgConfService;
import com.smartwebx.fr.util.ChartOptionCache;
import com.smartwebx.fr.util.TableDataConver;

@Controller
@RequestMapping("/chart")
public class SmartChartController {
	@Autowired
	private StoredProcService storedProcService;
	
	@Autowired
	private UseArgConfService useArgConfService;
	
	@RequestMapping("/getChartData")
	@ResponseBody
	public Object getChartData(Integer pageId, String code, Integer xPoint,
			Integer yPoint, Integer yPoint2) throws Exception {
		List<SimpleUseArgConf> simpleUseArgs = useArgConfService.getSimpleUseArgConfs(pageId);
		
		List<List<String>> result = storedProcService
				.getResultBySqlAndPageParam(code, simpleUseArgs, "table", false);
		TableDataConver tableDataConver = TableDataConver.getInstance(result);
		Map<String, Object> map = Maps.newHashMap();
		map.put("time",
				tableDataConver.getYListByTableAsY_Date(xPoint, "MM-dd"));
		
		List<Double> totalYDatas = Lists.newArrayList();
		List<Double> yAsixDatas = tableDataConver
				.getYListByTableAsY_Double(yPoint);
		totalYDatas.addAll(yAsixDatas);
		if (yPoint2 != null) {
			List<Double> yAsix2Datas = tableDataConver.getYListByTableAsY_Double(yPoint2);
			totalYDatas.addAll(yAsix2Datas);
			map.put("value2", yAsix2Datas);
		}
		map.put("value", yAsixDatas);
		
		if (!totalYDatas.isEmpty()) {
			// 根据数值计算最大值、最小值
			Double maxVal = Collections.max(totalYDatas);
			Double minVal = Collections.min(totalYDatas);
			minVal = Math.floor(minVal);
			maxVal = Math.ceil(maxVal);
			
			map.put("min", minVal);
			map.put("max", maxVal + (maxVal - minVal) * 0.2);
		}
		
		return map;
	}

	@RequestMapping(value = "/getChartOption", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getChartOption(String chartId) throws IOException {
		String data = ChartOptionCache.getOptionAndRemoveById(chartId);
		return "var options=" + data + ";";
	}
}